<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted, onUpdated, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import MeScroll from 'mescroll.js'
import 'mescroll.js/mescroll.min.css'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const form = reactive({
  id: 0,
  name: ''
})
// --mescroll--
const noData = proxy.$Global.noData
let mescroll = null
const items = ref([])

/* ---- */
const layer = ref()
const layerBox = ref()
const layerLoading = ref()

/* ---- */
// --getData--
const startMeScroll = () => {
  mescroll = new MeScroll(proxy.$refs.dataScroll, {
    up: {
      callback: getListData,
      isBounce: false,
      page: { num: 0, size: 20 },
      htmlNodata: '<p class="upwarp-nodata">-- 到底啦 --</p>',
      noMoreSize: 20,
      toTop: {
        src: '/pics/mescroll-totop.png',
        offset: 1000
      },
      empty: {
        warpId: proxy.$refs.dataList,
        tip: noData
      }
    }
  })
}
const getListData = (page) => {
  getListDataFromNet({
    forUrl: 'common-type/index',
    forData: {
      params: {
        'CommonTypeSearch[dealer_id]': logUser.id,
        // --电子合同计量单位--
        'CommonTypeSearch[type]': 4,
        // ----
        sort: 'SORT_DESC',
        // ----
        page: page.num,
        PageSize: page.size
      }
    }
  }, page.num, page.size, (curPageData) => {
    setListData(curPageData).then((result) => {
      mescroll.endSuccess(curPageData ? curPageData.length : 0, true)
      items.value = items.value.concat(result)
    })
  }, (resMsg) => {
    mescroll.endErr()
    proxy.$Myfun.forToast(layer.value, 'open', resMsg)
  })
}
const getListDataFromNet = (option, pageNum, pageSize, successCallback, errorCallback) => {
  if (Number(pageNum) === 1) {
    if (document.querySelector('.upwarp-nodata')) { document.querySelector('.upwarp-nodata').style.visibility = 'hidden' }
    items.value = []
  }
  // ----
  proxy.$http.get(option.forUrl, option.forData).then((res) => {
    successCallback && successCallback(res.items)
  }).catch((err) => { errorCallback && errorCallback(err) })
}
const setListData = async (items) => {
  const newItems = []
  for (let i = 0; i < Number(items.length); i++) {
    const item = items[i]
    // ----
    newItems.push({
      id: item.id,
      name: proxy.$Myfun.setText(item.name)
    })
  }
  return newItems
}
const divScroll = (event) => { proxy.$Myfun.setImgToTop() }
// ----
const emptyInfo = (event) => {
  const curEL = event.currentTarget
  const input = curEL.parentElement.querySelector('input')
  input.value = ''
  input.dispatchEvent(new Event('input'))
}
// ----
const checkInfoDel = async (item) => {
  let newItems = []
  const forSch = '"unit":"' + item.id + '"'
  await proxy.$http.get('contract/index', {
    params: {
      'ContractSearch[dealer_id]': logUser.id,
      'ContractSearch[pro_arr]': forSch,
      // --是否电子合同签字（针对未签字合同）--
      'ContractSearch[is_sign]': 0
    }
  }).then((res) => { newItems = res.items }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  if (Number(newItems.length) > 0) {
    proxy.$Myfun.forToast(layer.value, 'open', proxy.$Global.toast.noteUnit)
    return false
  }
  // ----
  const options = {
    content: proxy.$Global.layer.conDel,
    button: [{
      text: proxy.$Global.layer.btnCancel
    }, {
      text: proxy.$Global.layer.btnDel,
      class: 'xw-color-24',
      callback: async () => {
        layerBox.value.close()
        // ----
        await proxy.$http.delete('common-type/delete?id=' + item.id, {
          config_id: userInfo.config_id,
          openid: userInfo.openid
        }).then((res) => {}).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
        // ----
        mescroll.scrollTo(0)
        mescroll.resetUpScroll()
      }
    }]
  }
  proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
  // ----
  getAuditFun(4)
}
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      if (Number(form.name.length) === 0) getAuditFun(4)
      break
    }
    case 2: {
      form.id = item.id
      form.name = item.name
      break
    }
    case 3: {
      checkInfoDel(item)
      break
    }
    case 4: {
      form.id = 0
      form.name = ''
      break
    }
  }
}
// ----
const subform = async () => {
  if (Number(form.name.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写商品计量单位！')
    return false
  }
  // ----
  let forType = 'post'
  let forUrl = 'common-type/create'
  let forData = {
    dealer_id: logUser.id,
    // --电子合同计量单位--
    type: 4,
    // ----
    name: form.name,
    // ----
    config_id: userInfo.config_id,
    openid: userInfo.openid
  }
  if (Number(form.id) > 0) {
    forType = 'patch'
    forUrl = 'common-type/update?id=' + form.id
    forData = {
      name: form.name,
      // ----
      config_id: userInfo.config_id,
      openid: userInfo.openid
    }
  }
  // ----
  proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
  await proxy.$http[forType](forUrl, forData).then((res) => {}).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  proxy.$Myfun.disLoading(layerLoading.value, 'close')
  mescroll.scrollTo(0)
  mescroll.resetUpScroll()
  // ----
  getAuditFun(4)
}

/* ---- */
onMounted(() => {
  // --创建MeScroll对象--
  setTimeout(() => { startMeScroll() }, 500)
})
onUpdated(() => { nextTick(() => { proxy.$Myfun.setSectionH() }) })
onBeforeRouteLeave(() => { if (mescroll) mescroll.destroy() })
</script>

<template>
  <div>
    <header class="xw-bg-gray">
      <div class="forTop xw-flex xw-flex-align">
        <div class="TOP-sch xw-bg-white xw-radius-3 xw-flex-W1 xw-flex xw-flex-align">
          <p class="xw-flex-W1"><input class="text" type="text" placeholder="填写商品计量单位" v-model.trim="form.name" @blur="getAuditFun(1)"/></p>
          <transition name="fade"><em class="TOP-R fa fa-times-circle" @click="emptyInfo" v-if="form.name"></em></transition>
        </div>
        <span class="TOP-submit xw-WBlue xw-radius-3" @click="subform">提交</span>
      </div>
    </header>
    <div class="xw-section">
      <div ref="dataScroll" class="mescroll" @scroll="divScroll">
        <ul class="list-class xw-flex xw-flex-column" ref="dataList">
          <li class="xw-Tfg xw-bg-white xw-flex xw-flex-align" v-for="(item, index) in items">
            <div class="LCS-title xw-ellipsis xw-flex-W1">{{item.name}}</div>
            <div class="LCS-btn xw-act xw-flex xw-flex-align" @click="getAuditFun(2, item)"><em class="fa fa-edit"></em>修改</div>
            <div class="LCS-btn xw-act xw-flex xw-flex-align" @click="getAuditFun(3, item)"><em class="fa fa-trash-alt"></em>删除</div>
          </li>
        </ul>
      </div>
    </div>
    <layer-view ref="layer"/>
    <layer-view ref="layerBox"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>

<style scoped>
/* ---- */
.TOP-submit { margin-left: 1rem; }

/* ---- */
.list-class li { padding: 0 1rem; }
.list-class li:before { left: 1rem; }
.list-class li:nth-of-type(1):before { display: none; }
.LCS-title { font-size: 1.6rem; }
.LCS-btn { margin: 0 0 0 1.2rem; padding: 1.4rem 0; }
.LCS-btn em { margin-right: 0.5rem; color: #aaaaaa; }
</style>
